import streamlit as st
import time

# Initialize state variables if needed
if "final_output" not in st.session_state:
    st.session_state.final_output = ""

st.title("Karaoke-Style Rolling Text from LLM")

# A placeholder for our dynamic text
placeholder = st.empty()

# Simulate an LLM agent that yields content in multiple rounds.
# In practice, replace this with actual calls to your LLM.
def simulate_llm_output():
    # This could be token-by-token or line-by-line.
    # Here we just yield lines to simulate incremental output.
    content_rounds = [
        "Once upon a time, in a land far, far away...",
        "There lived a wise old turtle with stories to say...",
        "He told tales of heroes, of knights, and of kings...",
        "And whispered of treasures and magical things..."
    ]
    
    for round_text in content_rounds:
        # Simulate a streaming approach: output word by word
        words = round_text.split()
        for i, word in enumerate(words):
            yield word + (" " if i < len(words)-1 else "") 
            time.sleep(0.1)  # Simulate some delay in token generation

# Use a button to start the streaming process
if st.button("Generate Story"):
    st.session_state.final_output = ""  # Reset if needed

    for token in simulate_llm_output():
        # Append the new token to our cumulative text
        st.session_state.final_output += token
        # Update the placeholder with the complete text so far
        placeholder.markdown(st.session_state.final_output)

    st.success("Done generating!")
